<?php


namespace apps\marriage\core\model;

use think\facade\Db;
use vm\com\BaseModel;

class Adv extends BaseModel
{
    public function getByPositionId($positionId, $enabled = 1)
    {
        $res = $this->where('position_id', '=', $positionId)
                    ->where('enabled', '=', $enabled)
                    ->order('sort_order', 'ASC')
                    ->all();
        $data = [];
        if($res) {
            foreach ($res as $rs) {
                $data[] = $rs->getData();
            }
            return $data;
        }
        return $data;
    }

    public function getRandOneByPositionId($positionId)
    {
        $table = $this->getTable();
        $sql = 'SELECT * FROM '.$table.' AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM '.$table.' WHERE position_id='.$positionId.')-(SELECT MIN(id) FROM '.$table.' WHERE position_id='.$positionId.'))+(SELECT MIN(id) FROM '.$table.' WHERE position_id='.$positionId.')) AS id) AS t2 WHERE t1.id >= t2.id AND position_id='.$positionId.' ORDER BY t1.id LIMIT 1';
        $res = Db::query($sql);
        return $res ? $res[0] : null;
    }
}